package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.anno.GuiGuLogin;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.config.WxMaConfiguration;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	WxMaConfiguration wxMaConfiguration;

	@Autowired
	WxMaService wxMaService;

	@Autowired
	StringRedisTemplate redisTemplate;

	@Autowired
	KafkaService kafkaService;

	@Autowired
	UserPaidAlbumMapper userPaidAlbumMapper;

	@Autowired
	UserPaidTrackMapper userPaidTrackMapper;

	@Override
	public String wxLogin(String code) {
		if(code == null){
			throw new GuiguException(ResultCodeEnum.DATA_ERROR);
		}
		try {
			WxMaJscode2SessionResult sessionResult = wxMaService.getUserService().getSessionInfo(code);
			String openid = sessionResult.getOpenid();
			LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(UserInfo::getWxOpenId, openid);
			UserInfo userInfo = userInfoMapper.selectOne(lambdaQueryWrapper);
			if(userInfo == null){
				userInfo = new UserInfo();
				userInfo.setWxOpenId(openid);
				userInfo.setNickname("游客用户");
				userInfo.setStatus("1");
				userInfo.setAvatarUrl("https://q2.itc.cn/images01/20240514/ebbc4045a5be4db99c79ce784a89dc0a.png");
				userInfoMapper.insert(userInfo);
			}
			//TODO 发送异步请求
				kafkaService.sendMsg(KafkaConstant.QUEUE_USER_REGISTER, String.valueOf(userInfo.getId()));

			String token = new Date().getTime() + "";
			String redisLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
			redisTemplate.opsForValue().set(redisLoginKey,JSON.toJSONString(userInfo),RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);
			return token;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Override
	public UserInfo getUserInfo() {
		return userInfoMapper.selectById(AuthContextHolder.getUserId());
	}
	@Override
	public void updateUser(UserInfoVo userInfoVo) {
		Long userId = AuthContextHolder.getUserId();
		UserInfo userInfo = userInfoMapper.selectById(userId);
		userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
		userInfo.setNickname(userInfoVo.getNickname());
		userInfoMapper.updateById(userInfo);
	}

	@Override
	public Map<Long, Long> userIsPaidTrack(Long userId, Long albumId, List<Long> trackIdList) {
		Map<Long, Long> map = new HashMap<>();
		LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(UserPaidAlbum::getUserId,userId).eq(UserPaidAlbum::getAlbumId,albumId);
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(wrapper);
		if (userPaidAlbum != null){
			trackIdList.forEach(track-> map.put(track,1L));
		}else {
			LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(UserPaidTrack::getUserId,userId).eq(UserPaidTrack::getAlbumId,albumId).in(UserPaidTrack::getTrackId,trackIdList);
			List<UserPaidTrack> userPaidTracks = userPaidTrackMapper.selectList(queryWrapper);
			List<Long> longList = userPaidTracks.stream().map(UserPaidTrack::getTrackId).toList();
			trackIdList.forEach(track->{
				if (longList.contains(track)) {
					map.put(track,1L);
				}else {
					map.put(track,0L);
				}
			});
		}
		return map;
	}

	@Override
	public Boolean isPaidAlbum(Long albumId, Long userId) {
			LambdaQueryWrapper<UserPaidAlbum> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
			lambdaQueryWrapper.eq(UserPaidAlbum::getUserId , userId) ;
			lambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId , albumId) ;
			UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(lambdaQueryWrapper);
			return userPaidAlbum != null;
		}

	@Override
	public List<Long> findUserPaidTrackList(Long albumId) {
		// 获取当前登录用户的id
		Long userId = AuthContextHolder.getUserId();

		// 构建查询条件对象
		LambdaQueryWrapper<UserPaidTrack> lambdaQueryWrapper = new LambdaQueryWrapper<>() ;
		lambdaQueryWrapper.eq(UserPaidTrack::getAlbumId , albumId) ;
		lambdaQueryWrapper.eq(UserPaidTrack::getUserId , userId) ;
		List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(lambdaQueryWrapper);
		List<Long> trackIds = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());

		return trackIds;
	}
}
